<template>
	<div class="page-info">
		<div class="search">
			<div class="search-box">
				<a-form
					:model="searchInfo"
					:label-col="labelCol"
					:wrapper-col="wrapperCol"
				>
					<a-row :gutter="24">
						<a-col :span="8">
							<a-form-item
								:name="labelMap['code'].name"
								:label="labelMap['code'].label"
							>
								<a-input
									style="width: 90%; margin-left: 8px"
									v-model:value="(searchInfo as any).code"
									:placeholder="'请选择' + labelMap['code'].label"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item
								:name="labelMap['status'].name"
								:label="labelMap['status'].label"
							>
								<a-input
									style="width: 90%; margin-left: 8px"
									v-model:value="searchInfo.status"
									:placeholder="'请选择' + labelMap['status'].label"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<a-col style="text-align: right; margin-bottom: 20px">
							<a-space>
								<a-button type="primary" @click="query"> 查找</a-button>
								<a-button type="primary" @click="cancelQuery">清空</a-button>
							</a-space>
						</a-col>
					</a-row>
				</a-form>
			</div>
		</div>
		<div class="button" style="margin: 10px">
			<a-space>
				<a-button type="primary" @click="exportUserCommissionWithdrawal"
					>导出</a-button
				>
				<!-- <a-button type="primary" @click="editUserCommissionWithdrawal('add')"
					>新增</a-button
				> -->
				<!-- <a-button
					type="primary"
					danger
					@click="batchDelUserCommissionWithdrawal"
					>删除</a-button
				> -->
			</a-space>
		</div>
		<div class="content">
			<a-table
				:dataSource="dataSource"
				:columns="columns"
				:loading="loading"
				:row-key="(record: any) => record.id"
				:pagination="pagination"
				@change="handleTableChange"
				:scroll="{ y: 470 }"
				:row-selection="rowSelection"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'operation'">
						<a-space>
							<!-- <a-button type="primary" size="small" v-if="record.status === 'PENDING'"
                @click="submitUserCommissionWithdrawalInfo(record.id)">提现</a-button> -->
							<a-popconfirm
								title="确认删除?"
								ok-text="确认"
								cancel-text="取消"
								@confirm="delUserCommissionWithdrawal(record.id)"
								@cancel="cancel"
							>
								<a-button type="primary" size="small" danger>删除</a-button>
							</a-popconfirm>
						</a-space>
						<span></span>
					</template>
					<template v-else-if="column.key === 'status'">
						<a-tag v-if="record.status === 'CANCEL'" color="red">取消</a-tag>
						<a-tag v-if="record.status === 'PENDING'" color="blue"
							>待处理</a-tag
						>
						<a-tag v-else-if="record.status === 'COMPLETED'" color="green"
							>已完成</a-tag
						>
					</template>
					<template v-else-if="column.key === 'withdrawalDate'">
						<span>{{
							dayjs(record.withdrawalDate).format('YYYY-MM-DD HH:mm:ss')
						}}</span>
					</template>
				</template>
			</a-table>
			<UserCommissionWithdrawalDetail
				ref="editInfo"
				:open="visible"
				:modelInfo="modelInfo"
				@handleOk="handleOk"
				@handleCancel="handleCancel"
			></UserCommissionWithdrawalDetail>
		</div>
	</div>
</template>
<script setup lang="ts">
import {
	SearchInfo,
	pagination,
	columns,
	DataItem,
	ModelInfo,
	pageInfo,
} from './userCommissionWithdrawalListTs';
import {
	getUserCommissionWithdrawalPage,
	deleteUserCommissionWithdrawal,
	submitUserCommissionWithdrawal,
	exportUserCommissionWithdrawal as apiExportUserCommissionWithdrawal,
} from '@/api/userInfo/userCommissionWithdrawal/userCommissionWithdrawalTs';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

const labelCol = ref({ span: 5 });
const wrapperCol = ref({ span: 19 });

let rowIds = [] as any;

const rowSelection = ref({
	checkStrictly: false,
	onChange: (
		selectedRowKeys: (string | number)[],
		selectedRows: DataItem[],
	) => {
		rowIds = selectedRowKeys;
	},
	onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
		console.log(record, selected, selectedRows);
	},
	onSelectAll: (
		selected: boolean,
		selectedRows: DataItem[],
		changeRows: DataItem[],
	) => {
		console.log(selected, selectedRows, changeRows);
	},
});

const labelMap = ref<any>({
	userId: { name: 'userId', label: '用户ID，关联用户表' },
	code: { name: 'code', label: '用户编码' },
	withdrawalAmount: { name: 'withdrawalAmount', label: '提现金额' },
	withdrawalDate: { name: 'withdrawalDate', label: '提现申请时间' },
	status: { name: 'status', label: '提现状态' },
	notes: { name: 'notes', label: '备注或说明' },
});

let searchInfo = ref<SearchInfo>({});

const cancelQuery = (): void => {
	searchInfo.value = {};
};

const query = (): void => {
	getUserCommissionWithdrawalListPage(searchInfo.value, pagination.value);
};

const handleTableChange = (pagination): void => {
	getUserCommissionWithdrawalListPage(searchInfo.value, pagination);
};

const delUserCommissionWithdrawal = (ids: string): void => {
	deleteUserCommissionWithdrawal(ids).then((res) => {
		if (res.code == '200') {
			message.success((res && '删除' + res.message) || '删除成功！', 3);
			getUserCommissionWithdrawalListPage(searchInfo.value, pagination.value);
		} else {
			message.error((res && res.message) || '删除失败！', 3);
		}
	});
};

const submitUserCommissionWithdrawalInfo = async (id: number) => {
	let res = await submitUserCommissionWithdrawal(id);
	console.log(`ddddddddddddddddddddddddddddddddddddddddddddddddddddddd`, res);
	const { code, data, message: messageInfo } = res;
	console.log(`ddddddddddddeeeeeeeeeeeeeeeeeeee`, code, data, messageInfo);
	if (code === '200') {
		getUserCommissionWithdrawalListPage(searchInfo.value, pagination.value);
		message.success(messageInfo || '成功！');
	} else {
		message.warn(messageInfo || '失败，请联系管理员！');
	}
};

const batchDelUserCommissionWithdrawal = (): void => {
	let ids = '';
	if (rowIds && rowIds.length > 0) {
		rowIds.forEach((item: string) => {
			ids += item + ',';
		});
		ids = ids.substring(0, ids.length - 1);
	} else {
		message.warning('请先选择数据！', 3);
		return;
	}
	delUserCommissionWithdrawal(ids);
};

let loading = ref<boolean>(false);

let dataSource = ref();

const cancel = (e: MouseEvent): void => {
	console.log(e);
};

const getUserCommissionWithdrawalListPage = (
	param: SearchInfo,
	cur: pageInfo,
): void => {
	loading.value = true;
	getUserCommissionWithdrawalPage(param, cur.current, cur.pageSize)
		.then((res) => {
			if (res.code == '200') {
				dataSource.value = res.data.records;
				pagination.value.current = res.data.current;
				pagination.value.pageSize = res.data.size;
				pagination.value.total = res.data.total;
			} else {
				message.error((res && res.message) || '查询列表失败！');
			}
		})
		.finally(() => {
			loading.value = false;
		});
};

const init = (): void => {
	//获取用户提现回佣金额历史表页面数据
	getUserCommissionWithdrawalListPage(searchInfo.value, pagination.value);
};

init();

let visible = ref<boolean>(false);

let modelInfo = ref<ModelInfo>({});

//新增和修改弹窗
const editUserCommissionWithdrawal = (type: string, id?: number): void => {
	if (type == 'add') {
		modelInfo.value.title = '新增明细';
		modelInfo.value.id = undefined;
	} else if (type == 'update') {
		modelInfo.value.title = '修改明细';
		modelInfo.value.id = id;
	}
	modelInfo.value.confirmLoading = true;
	visible.value = true;
};

const handleOk = (v: boolean): void => {
	visible.value = v;
	getUserCommissionWithdrawalListPage(searchInfo.value, pagination.value);
};

const handleCancel = (v: boolean): void => {
	visible.value = v;
};

const exportUserCommissionWithdrawal = () => {
	apiExportUserCommissionWithdrawal(searchInfo.value, { responseType: 'blob' })
		.then((response: any) => {
			const blob = new Blob([response.data], {
				type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
			});
			const url = window.URL.createObjectURL(blob);
			const link = document.createElement('a');
			link.href = url;
			link.setAttribute('download', '佣金提现记录.xlsx');
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
			window.URL.revokeObjectURL(url);
		})
		.catch((error: any) => {
			console.error('Error exporting Excel:', error);
		});
};
</script>
<style lang="scss" scoped></style>
